﻿using System;
using System.Web;
using System.Net.Mail;
using CE.Company;

namespace CE.Mail
{
    public class MailManagerTH
    {
        #region Private Variable
        private MailMessage mail = null;
        private MailAddress mailAddress = null;
        private SmtpClient mailClient = null;
        private int clientPort = -1;
        private string clientHost = String.Empty;
        private bool isEnabledSsl = false;
        private int mailType = -1;
        private string mailBody = "";
        private MailPriority mailPriority = MailPriority.Normal;

        //static string smtphost = System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPHostName"].ToString();
        //static string smtpport = System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPPort"].ToString();
        //static string smtpaccount = System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPAccount"].ToString();
        //static string smtpauthcode = System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPAuthCode"].ToString();
        //static bool smtpenablessl = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPSslEnable"].ToString());
        //static string smtpdisplayname = System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPDisplayName"].ToString();
        //static string smtpreplyto = System.Configuration.ConfigurationSettings.AppSettings["TH.SMTPReplyTo"].ToString();

        static string smtphost = "smtp.gmail.com";
        static string smtpport = "587";
        static string smtpaccount = "service@gluaygluay.com";
        static string smtpauthcode = "ByeBye-Sop13Che";
        static bool smtpenablessl = true;
        static string smtpdisplayname = "GluayGluay.com Support";
        static string smtpreplyto = "service@gluaygluay.com";

        #endregion

        public MailManagerTH()
        {
            mailClient = new SmtpClient();
            mailClient.Host = "smtp.jaring.my";
            mailClient.Port = 587;
            mailClient.EnableSsl = true;
        }

        public MailManagerTH(string HostName, string Port, bool EnableSSL, string Account, string AuthCode)
        {
            smtphost = HostName;
            smtpenablessl = EnableSSL;
            smtpport = Port;
            smtpaccount = Account;
            smtpauthcode = AuthCode;
        }

        public static bool SendWelcomeMessage(string EmailAddress, string CCEmailAddress, string BCCEmailAddress, string EmailSubject, string EmailMessage)
        {            
            bool _result = SendMail(smtphost,
                        587,
                        smtpaccount,
                        smtpauthcode,
                        smtpdisplayname, //"กล้วยๆ.com",
                        smtpaccount,
                        "GluayGluay.com",                       
                        EmailAddress,
                        CCEmailAddress,
                        BCCEmailAddress,
                        smtpreplyto,
                        EmailSubject,
                        EmailMessage,
                        smtpenablessl);
            return _result;
        }

        public static bool SendMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sReplyToEmail, string sHeader, string sMessage, bool fSSL)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            //System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();

            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
            //if (fSSL)
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

            //if (sUserName.Length == 0)
            //{
            //    //Ingen auth 
            //}
            //else
            //{
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
            //}

            //Mail.To = sToEmail;
            //Mail.Cc = sCCEmail;
            //Mail.Bcc = sBCCEmail;
            //Mail.From = sFromEmail;
            //Mail.Subject = sHeader;
            //Mail.Body = sMessage;            
            //Mail.BodyFormat = System.Web.Mail.MailFormat.Html;

            try
            {
                MailMessage Mail = new MailMessage();

                if (sToEmail != "")
                {
                    string[] sGetToEmails = sToEmail.Split(';');

                    foreach (string toemail in sGetToEmails)
                    {
                        if (toemail != "")
                            Mail.To.Add(new MailAddress(toemail));
                    }
                }

                if (sCCEmail != "")
                {
                    string[] sGetCCEmails = sCCEmail.Split(';');

                    foreach (string ccemail in sGetCCEmails)
                    {
                        if (ccemail != "")
                            Mail.CC.Add(new MailAddress(ccemail));
                    }
                }

                if (sBCCEmail != "")
                {
                    string[] sGetBCCEmails = sBCCEmail.Split(';');

                    foreach (string bccemail in sGetBCCEmails)
                    {
                        if (bccemail != "")
                            Mail.Bcc.Add(new MailAddress(bccemail));
                    }

                }

                Mail.From = new MailAddress(sFromEmail, sFromName); ;
                Mail.Subject = sHeader;
                Mail.Body = sMessage;
                Mail.IsBodyHtml = true;
                Mail.ReplyTo = new MailAddress(sReplyToEmail);


                //System.Web.Mail.SmtpMail.SmtpServer = sHost;
                //System.Web.Mail.SmtpMail.Send(Mail);                

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                object userState = Mail;

                smtp.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                smtp.SendAsync(Mail, userState);

            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMailNew Exception");

                return false;
            }
            return true;
        }

        static void MailDeliveryComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //Console.WriteLine("Message \"{0}\".", e.UserState);

            if (e.Error != null)
            {
                try
                {
                    //Get the Original MailMessage object
                    MailMessage mail = (MailMessage)e.UserState;

                    //write out the subject
                    string subject = mail.Subject;

                    System.Text.StringBuilder errorMsg = new System.Text.StringBuilder();
                    errorMsg.Append(string.Format("An error occurred sending message [{0}]. {1}", e.UserState.ToString(), e.Error.Message));

                    if (e.Error.InnerException != null)
                        errorMsg.Append(Environment.NewLine + "Inner exception message: " + e.Error.InnerException.Message);

                    errorMsg.Append(Environment.NewLine + "Subject: " + subject);
                    errorMsg.Append(Environment.NewLine + "Sender: " + mail.Sender.Address.ToString());
                    errorMsg.Append(Environment.NewLine + "Sender Host: " + mail.Sender.Host.ToString());
                    errorMsg.Append(Environment.NewLine + "From : " + mail.From.Address.ToString());
                    errorMsg.Append(Environment.NewLine + "From Host : " + mail.From.Host.ToString());
                    string _toAddresses = "";
                    foreach (MailAddress _msgMail in mail.To)
                    {
                        _toAddresses += _msgMail.Address.ToString() + ";";
                    }
                    errorMsg.Append(Environment.NewLine + "To : " + _toAddresses);
                    CreateMailDeliveryExceptionLog("SendMailNew MailDeliveryComplete Exception", errorMsg);
                }
                catch (Exception Ex)
                {
                    Ex = null;
                }
            }
            else if (e.Cancelled)
            {
                //Console.WriteLine("Sending of email cancelled.");
            }
            else
            {
                //Console.WriteLine("Message sent.");
            }
        }

        private static void CreateMailDeliveryExceptionLog(string strLocation, System.Text.StringBuilder ErrorMessage)
        {
            String[] _fileContent = new String[3];
            _fileContent[0] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[1] = "Location : " + "MyMailManager - " + strLocation;
            _fileContent[2] = "Message : " + ErrorMessage;

            WriteMailDeliveryExceptionLog("MailDelivery_", _fileContent);
        }

        private static void WriteMailDeliveryExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                CE.InputOut.MyIO _newFile = new CE.InputOut.MyIO();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + DateTime.Now.Day.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("00") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }

        /*//Sakthi on 11/Nov/2011
        public static bool SendMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sToCCEmail, string sToBCCEmail, string sHeader, string sMessage, bool fSSL)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();
            Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
            Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
            if (fSSL)
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

            if (sUserName.Length == 0)
            {
                //Ingen auth 
            }
            else
            {
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
            }

            Mail.To = sToEmail;
            Mail.From = sFromEmail;
            Mail.Subject = sHeader;
            Mail.Body = sMessage;
            Mail.Cc = sToCCEmail;
            Mail.Bcc = sToBCCEmail;
            //Mail.BodyEncoding = System.Text.Encoding.Unicode;
            Mail.BodyFormat = System.Web.Mail.MailFormat.Html;
            try
            {
                System.Web.Mail.SmtpMail.SmtpServer = sHost;
                System.Web.Mail.SmtpMail.Send(Mail);
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMail Exception");
                return false;
            }
            return true;
        }
        //Sakthi on 11/Nov/2011 */

        private static void CreateExceptionLog(Exception Ex, string EmailSettingInfo, string strLocation)
        {
            String[] _fileContent = new String[7];
            _fileContent[0] = "Email Setting : " + EmailSettingInfo;
            _fileContent[1] = "Source : " + Ex.Source;
            _fileContent[2] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[3] = "Stack Trace :" + Ex.StackTrace.ToString();
            _fileContent[4] = "Target Site : " + Ex.TargetSite.ToString();
            _fileContent[5] = "Location : " + "MyMailManager - " + strLocation;
            _fileContent[6] = "Message : " + Ex.Message;

            WriteExceptionLog("Mail_", _fileContent);
        }

        private static void WriteExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                CE.InputOut.MyIO _newFile = new CE.InputOut.MyIO();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + DateTime.Now.Day.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("00") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }

        //Sakthi on 25 May 2011 -- Start
        public static bool SendCarProposalToUser(string PName, string ToEmail, string CCEmail, string BCCEmail, string InsType, string Date, string Time, string RefNo)
        {
            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "http://" + myUri.Host;
            string ConfirmPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ProviderPath");

            string confirmUrl = domainUrl;
            string imgUrl = domainUrl;

            confirmUrl += ConfirmPath;

            imgUrl += CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");

            CompanyInformation _company = new CompanyInformation();
            CompanyInformationDB _companydb = new CompanyInformationDB();
            _company = _companydb.GetCompanyInformation(1);
            string _companyAddress = "";
            string _emailaddress = "";
            if (_company != null)
            {
                _companyAddress = _company.Address1;
                _emailaddress = _company.EmailAddress;
            }
            _company = null;
            _companydb = null;

            string mailBody = "<br>Proposal Reference : " + RefNo + "<br><br>";
            mailBody += "Thank you. Your completed car insurance application is received.<br><br>";
            mailBody += "CompareXpress will either call or email you the confirmation within 3 working days.<br><br>";
            mailBody += "If you have queries, you may contact 02-268 8222 or email <a href='mailto:support@comparexpress.co.th'>support@comparexpress.co.th</a>.<br><br>";
            mailBody += "<br>Best Regards,<br/><br>";
            mailBody += "Customer Support<br/>";
            mailBody += "<br><br><img src='" + imgUrl + "' /><br>";
            mailBody += "<hr align='left' width='410px' /><br>";
            mailBody += "<b>CompareXpress Non-Life Insurance Broker (Thailand) Ltd.</b><br>";
            mailBody += "42nd Floor, United Center Building,<br />";
            mailBody += "323 Silom Road, Bangrak,<br />";
            mailBody += "Bangkok 10500<br />";
            mailBody += "t : +66 2 268 8222<br />";
            mailBody += "f : +66 2 266 6321 <br />";
            mailBody += "<a href='mailto:support@comparexpress.co.th'>e : support@comparexpress.co.th</a>";
            mailBody += "<hr align='left' width='410px'  /><br>";
            mailBody += "<i>This is a computer-generated email. Please do not reply to this email.</i> ";

            string cxformssmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPHostName");
            string cxformssmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPPort");
            string cxformssmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPAccount");
            string cxformssmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPAuthCode");
            string cxformssmtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPDisplayName");
            string cxformssmtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPPReplyTo");
            bool cxformssmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPSslEnable"));

            bool _result = SendMail(cxformssmtphost,
                        Convert.ToInt32(cxformssmtpport),
                        cxformssmtpaccount,
                        cxformssmtpauthcode,
                        cxformssmtpdisplayname,// "<CX> Email Confirmation to Participating Customer",
                        cxformssmtpaccount,
                        PName,
                        ToEmail,
                        CCEmail,
                        BCCEmail,
                        cxformssmtpreplyto,
                        InsType + " Application Form (Reference No : " + RefNo + ") - from CompareXpress.co.th",
                        mailBody,
                        cxformssmtpenablessl);
            return _result;
        }
        //Sakthi on 25 May 2011 -- End

        //Sakthi on 02 Jun 2011 -- Start
        public static bool SendCarProposalNotificationToUser(string PName, string ToEmail, string CCEmail, string BCCEmail, string InsType, string Date, string Time, string RefNo, string PaymentType)
        {
            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
            string imgUrl = domainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");
            
            //string domainUrl = "http://" + myUri.Host;
            //string imgUrl = domainUrl;
            //imgUrl += CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");
            string ConfirmPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ProviderPath");

            string confirmUrl = domainUrl;
            confirmUrl += ConfirmPath;
                                  

            CompanyInformation _company = new CompanyInformation();
            CompanyInformationDB _companydb = new CompanyInformationDB();
            _company = _companydb.GetCompanyInformation(1);
            string _companyAddress = "";
            string _emailaddress = "";
            if (_company != null)
            {
                _companyAddress = _company.Address1;
                _emailaddress = _company.EmailAddress;
            }
            _company = null;
            _companydb = null;

            string mailBody = "<br>"+ Resources.WelcomeEmail .ProposalReference + " : " + RefNo + "<br><br>";
            mailBody += Resources.WelcomeEmail.ProposalMessage1 + "<br><br>";
            mailBody += Resources.WelcomeEmail.ProposalMessage2 +"<br><br>";
            mailBody += Resources.WelcomeEmail.ProposalMessage3 + " <a href='mailto:support@gluaygluay.cocom'> support@gluaygluay.com</a>.<br><br>";
            mailBody += "<br>"+ Resources.WelcomeEmail .BestRegards + ",<br/><br>";
            mailBody += Resources .WelcomeEmail .CustomerSupport +"<br/>";
            mailBody += "<br><br><img src='" + imgUrl + "' /><br>";
            mailBody += "<hr align='left' width='410px' /><br>";
            mailBody += "<b>CompareXpress Non-Life Insurance Broker (Thailand) Ltd.</b><br>";
            mailBody += "42nd Floor, United Center Building,<br />";
            mailBody += "323 Silom Road, Bangrak,<br />";
            mailBody += "Bangkok 10500<br />";
            mailBody += "t : +66 2 268 8222<br />";
            mailBody += "f : +66 2 266 6321 <br />";
            mailBody += "<a href='mailto:support@gluaygluay.com'>e : support@gluaygluay.com</a>";
            mailBody += "<hr align='left' width='410px'  /><br>";
            mailBody += "<i>This is a computer-generated email. Please do not reply to this email.</i> ";

            string cxformssmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPHostName");
            string cxformssmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPPort");
            string cxformssmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPAccount");
            string cxformssmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPAuthCode");
            string cxformssmtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPDisplayName");
            string cxformssmtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPPReplyTo");
            bool cxformssmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPSslEnable"));

            bool _result = SendMail(cxformssmtphost,
                        Convert.ToInt32(cxformssmtpport),
                        cxformssmtpaccount,
                        cxformssmtpauthcode,
                        cxformssmtpdisplayname, // "<GG> Email Confirmation to Participating Customer",
                        cxformssmtpaccount,
                        PName,
                        ToEmail,
                        CCEmail,
                        BCCEmail,
                        cxformssmtpreplyto,
                        InsType + " [" + PaymentType + "]  (" + Resources.WelcomeEmail.ReferenceNo + " : " + RefNo + ") - from GluayGluay.com",
                        mailBody,
                        cxformssmtpenablessl);
            return _result;
        }
        //Not using
        public static bool SendCarProposalNotificationToUser(string PName, string ToEmail, string CCEmail, string BCCEmail, string InsType, string Date, string Time, string RefNo, string PaymentType, bool Status)
        {
            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "http://" + myUri.Host;
            string ConfirmPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ProviderPath");

            string confirmUrl = domainUrl;
            string imgUrl = domainUrl;

            confirmUrl += ConfirmPath;

            imgUrl += CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");

            CompanyInformation _company = new CompanyInformation();
            CompanyInformationDB _companydb = new CompanyInformationDB();
            _company = _companydb.GetCompanyInformation(1);
            string _companyAddress = "";
            string _emailaddress = "";
            if (_company != null)
            {
                _companyAddress = _company.Address1;
                _emailaddress = _company.EmailAddress;
            }
            _company = null;
            _companydb = null;

            string mailBody = "<br>Proposal Reference : " + RefNo + "<br><br>";
            if (PaymentType == "BI")
            {
                mailBody += "Thank you. Your completed car insurance application is received.<br><br>";
                mailBody += "CompareXpress will either call or email you the confirmation within 3 working days.<br><br>";
                mailBody += "If you have queries, you may contact 02-268 8222 or email <a href='mailto:support@comparexpress.co.th'>support@comparexpress.co.th</a>.<br><br>";
            }
            else if (PaymentType == "CC")
            {
                mailBody += "Thank you. Your completed car insurance application is received.<br><br>";
                if (Status == true)
                {
                    mailBody += "CompareXpress will either call or email you the confirmation within 3 working days.<br><br>";
                }
                else
                {
                    mailBody += "Your Credit Card Payment Failed.<br><br>";
                }
                mailBody += "If you have queries, you may contact 02-268 8222 or email <a href='mailto:support@comparexpress.co.th'>support@comparexpress.co.th</a>.<br><br>";
            }
            mailBody += "<br>Best Regards,<br/><br>";
            mailBody += "Customer Support<br/>";
            mailBody += "<br><br><img src='" + imgUrl + "' /><br>";
            mailBody += "<hr align='left' width='410px' /><br>";
            mailBody += "<b>CompareXpress Non-Life Insurance Broker (Thailand) Ltd.</b><br>";
            mailBody += "42nd Floor, United Center Building,<br />";
            mailBody += "323 Silom Road, Bangrak,<br />";
            mailBody += "Bangkok 10500<br />";
            mailBody += "t : +66 2 268 8222<br />";
            mailBody += "f : +66 2 266 6321 <br />";
            mailBody += "<a href='mailto:support@comparexpress.co.th'>e : support@comparexpress.co.th</a>";
            mailBody += "<hr align='left' width='410px'  /><br>";
            mailBody += "<i>This is a computer-generated email. Please do not reply to this email.</i> ";

            string cxformssmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPHostName");
            string cxformssmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPPort");
            string cxformssmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPAccount");
            string cxformssmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPAuthCode");
            string cxformssmtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPDisplayName");
            string cxformssmtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPPReplyTo");
            bool cxformssmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CXFormsSMTPSslEnable"));

            bool _result = SendMail(cxformssmtphost,
                        Convert.ToInt32(cxformssmtpport),
                        cxformssmtpaccount,
                        cxformssmtpauthcode,
                        cxformssmtpdisplayname, //"<CX> Email Confirmation to Participating Customer",
                        cxformssmtpaccount,
                        PName,
                        ToEmail,
                        CCEmail,
                        BCCEmail,
                        cxformssmtpreplyto,
                        InsType + " Application Form (Reference No : " + RefNo + ") - from CompareXpress.co.th",
                        mailBody,
                        cxformssmtpenablessl);
            return _result;
        }
        //Sakthi on 02 Jun 2011 -- End

        public static bool SendMailWithAttach(string CustName, string EmailAddress, string CCEmail, string BCCEmail, string EmailSubject, string EmailMessage, string[] fileList)
        {
            //string smtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPHostName");
            //string smtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPPort");
            //string smtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPAccount");
            //string smtpdisplyname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPDisplayName");
            //string smtpreplytoemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPReplyTo");
            //string smtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPAuthCode");
            //bool smtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.InternalSMTPSslEnable"));


            string IsLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");
            if (IsLive == "0" || IsLive == "2")
            {
                EmailSubject = "[TS] " + EmailSubject;
            }

            bool _result = SendGGMailNewByAttachments(smtphost,
                        Convert.ToInt32(smtpport),
                        smtpaccount,
                        smtpauthcode,
                        smtpdisplayname,
                        smtpaccount,
                        CustName,
                        EmailAddress,
                        CCEmail,
                        BCCEmail,
                        smtpreplyto,
                        EmailSubject,
                        EmailMessage,
                        smtpenablessl, fileList);
            return _result;
        }

        public static bool SendGGMailNewByAttachments(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
       string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sReplyToEmail, string sHeader, string sMessage, bool fSSL, string[] fileList)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            MailMessage Mail = new MailMessage();
            try
            {
                if (sToEmail != "")
                {
                    string[] sGetToEmails = sToEmail.Split(';');

                    foreach (string toemail in sGetToEmails)
                    {
                        if (toemail != "")
                            Mail.To.Add(new MailAddress(toemail));
                    }
                }

                if (sCCEmail != "")
                {
                    string[] sGetCCEmails = sCCEmail.Split(';');

                    foreach (string ccemail in sGetCCEmails)
                    {
                        if (ccemail != "")
                            Mail.CC.Add(new MailAddress(ccemail));
                    }
                }

                if (sBCCEmail != "")
                {
                    string[] sGetBCCEmails = sBCCEmail.Split(';');

                    foreach (string bccemail in sGetBCCEmails)
                    {
                        if (bccemail != "")
                            Mail.Bcc.Add(new MailAddress(bccemail));
                    }

                }

                Mail.From = new MailAddress(sFromEmail, sFromName);
                Mail.Subject = sHeader;
                Mail.Body = sMessage;
                Mail.IsBodyHtml = true;
                Mail.ReplyTo = new MailAddress(sReplyToEmail);

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                object userState = Mail;

                for (int i = 0; i < fileList.Length; i++)
                {
                    Mail.Attachments.Add(new Attachment(fileList[i].ToString()));
                }

                smtp.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                //smtp.SendAsync(Mail, userState);
                smtp.Send(Mail);
                
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMailNew By Attachments Exception");

                return false;
            }
            finally
            {
                Mail.Dispose();
            }
            return true;
        }


    }
}